from io import BytesIO
from sqlalchemy import text

from flask import Blueprint, request, jsonify, send_from_directory, make_response, send_file
from openpyxl.reader.excel import load_workbook

import app
from .exchange import get_check_code, iqiyi_invoke, mgtv_invoke, wps_invoke
from .models import User, Phone, AppVip, App, RedeemCode, ShopVip
from functools import wraps
from . import db
import bcrypt
import jwt
from datetime import datetime, timedelta
import os
from openpyxl import Workbook
import uuid


def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Token is missing'}), 401
        try:
            data = jwt.decode(token.split()[1], os.getenv('SECRET_KEY', 'secret'), algorithms=['HS256'])
            user = User.query.get(data['user_id'])
            if not user or user.role != 'admin':
                return jsonify({'message': 'Admin access required'}), 403
        except:
            return jsonify({'message': 'Token is invalid'}), 401

        return f(*args, **kwargs)

    return decorated_function


main = Blueprint('main', __name__)


@main.route('/')
def index():
    token = request.cookies.get('token')
    if token:
        try:
            jwt.decode(token, os.getenv('SECRET_KEY', 'secret'), algorithms=['HS256'])
            return send_from_directory('templates', 'index.html')
        except:
            pass
    return send_from_directory('templates', 'login.html')


@main.route('/user_proto/<code>')
def user_proto(code):
    shop_vip = ShopVip.query.filter(ShopVip.url_addr == code).filter(ShopVip.url_valid == 1).first()
    if shop_vip is None:
        return send_from_directory('templates', 'invalid.html')

    return send_from_directory('templates', 'user_proto.html')


@main.route('/search_by_code', methods=['POST'])
def search_by_code():
    params = request.get_json()
    shop_vip = ShopVip.query.filter(ShopVip.url_addr == params.get('code')).filter(ShopVip.url_valid == 1).first()
    return jsonify({"phone_num": shop_vip.phone_num, "country_code": shop_vip.country_code}), 200


@main.route('/call_check_code', methods=['POST'])
def call_check_code():
    params = request.get_json()
    phone_num = params.get('phone_num')
    phone = Phone.query.filter(Phone.phone_num == phone_num).first()
    code = get_check_code(phone.phone_code_url)
    return jsonify({"check_code": code}), 200


@main.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return send_from_directory('templates', 'login.html')

    try:
        # 验证请求数据
        data = request.get_json()
        if not data or 'password' not in data:
            return jsonify({
                'status': 'error',
                'code': 400,
                'message': 'Missing required fields'
            }), 400

        # 查询用户
        user = User.query.filter_by(username=data.get('username'), role='admin').first()
        if not user:
            return jsonify({
                'status': 'error',
                'code': 401,
                'message': 'Invalid credentials'
            }), 401

        # 验证密码
        if not bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')):
            return jsonify({
                'status': 'error',
                'code': 401,
                'message': 'Invalid credentials'
            }), 401

        # 生成token
        token = jwt.encode({
            'user_id': user.id,
            'exp': datetime.utcnow() + timedelta(hours=1)
        }, os.getenv('SECRET_KEY', 'secret'))

        response = make_response(jsonify({
            'status': 'success',
            'code': 200,
            'data': {
                'token': token,
                'user_id': user.id,
                'username': user.username,
                'role': user.role
            }
        }), 200)
        response.set_cookie('token', token, httponly=True, secure=True, samesite='Lax')
        return response

    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'status': 'error',
            'code': 500,
            'message': 'Internal server error',
            'detail': str(e)
        }), 500


@main.route('/phone/search', methods=['POST'])
def get_phone_page():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = Phone.query
    phone_num = params.get('phone_num', None)
    carrier = params.get('carrier', None)
    has_vip = params.get('has_vip', None)
    result = []
    if phone_num is not None and phone_num != '':
        query = query.filter(Phone.phone_num.contains(phone_num))
    if carrier is not None and carrier != '':
        query = query.filter(Phone.carrier == carrier)
    if has_vip is not None and has_vip != '':
        query = query.filter(Phone.has_vip == has_vip)
    total = query.count()
    phone_list = query.limit(page_size).offset(page_offset)
    for phone in phone_list:
        result.append({
            'id': phone.id,
            'country_code': phone.country_code,
            'phone_num': phone.phone_num,
            'phone_code_url': phone.phone_code_url,
            'app_type': phone.app_type,
            'carrier': phone.carrier,
            'has_vip': phone.has_vip,
            'created_at': phone.created_at
        })
    return jsonify({'total': total, 'list': result}), 200

# 手机号模版下载
@main.route('/phone/download', methods=['POST'])
def phone_template_download():
    wb = Workbook()
    ws = wb.active
    ws.title = 'Sheet'
    ws.append(["序号", "国际区号", "手机号", "获取验证码url", "app类型", "运营商"])
    ws.append(["1、", "+1", "18612344321", "http://123", "mgtv", "电信"])
    ws.append(["", "", "", "", "", ""])
    ws.append(["app类型对应关系", "实际值", "展示值", "", "", ""])
    ws.append(["", "mgtv", "芒果tv", "", "", ""])
    ws.append(["", "txsp", "腾讯视频", "", "", ""])
    ws.append(["", "iqy", "爱奇艺", "", "", ""])
    ws.append(["", "wps", "WPS", "", "", ""])
    ws.append(["", "yksp", "优酷视频", "", "", ""])
    output = BytesIO()
    wb.save(output)
    output.seek(0)

    return send_file(output,
                     as_attachment=True,
                     download_name="手机号模版.xlsx",
                     mimetype='application/vnd.ms-excel')

# 手机号导入
@main.route('/phone/upload', methods=['POST'])
def phone_upload():
    file = request.files['file']

    wb = load_workbook(file)
    ws = wb.worksheets[0]

    for row in ws.iter_rows(min_row=2, values_only=True):
        try:
            new_phone = Phone(
                country_code = row[1],
                phone_num = row[2],
                phone_code_url = row[3],
                app_type = row[4],
                carrier = row[5]
            )

            db.session.add(new_phone)
            db.session.commit()

        except Exception as e:
            db.session.rollback()

    return jsonify({'msg':'导入成功'}), 200

# 兑换会员 国际区号 手机号 获取验证码接口 app类型 会员类型 会员周期
@main.route('/phone/exchange_vip', methods=['POST'])
def exchange_vip():
    params = request.get_json()
    country_code = params.get('country_code', None)
    phone_num = params.get('phone_num', None)
    phone_code_url = params.get('phone_code_url', None)
    app_type = params.get('app_type', None)
    vip_type = params.get('vip_type', None)
    vip_cycle = params.get('vip_cycle', None)

    try:
        res = exchange_vip_method(country_code, phone_num, phone_code_url, app_type, vip_type, vip_cycle)
        if res != 1:
            return res

        return jsonify({'msg': '兑换成功'}), 200
    except Exception as e:
        return jsonify({
            'msg': str(country_code) + '-' + str(phone_num) + '-' + str(app_type) + '- 兑换失败',
            'code': 1,
        }), 200

def exchange_vip_method(country_code, phone_num, phone_code_url, app_type, vip_type, vip_cycle):

    # 更新手机号这条为已开通
    phone = Phone.query.filter(Phone.country_code == country_code).filter(Phone.phone_num == phone_num).first()
    if phone is None:
        return '未找到手机号-' + str(country_code) + '-' + str(phone_num)

    if phone.has_vip == 1:
        return '已开通会员-' + str(country_code) + '-' + str(phone_num)

    phone.has_vip = 1

    # 更新兑换码为已使用
    redeem = (RedeemCode.query.filter(RedeemCode.app_name == app_type)
                              .filter(RedeemCode.vip_type == vip_type)
                              .filter(RedeemCode.vip_cycle == vip_cycle)
                              .filter(RedeemCode.use_status == 0).first())
    if redeem is None:
        return '找不到兑换码-' + str(app_type) + '-' + str(vip_type) + '-' + str(vip_cycle),

    redeem.use_status = 1

    # 查询会员可分享数量
    query_app = (App.query.filter(App.app_name == app_type)
                 .filter(App.vip_type == vip_type)
                 .filter(App.vip_cycle == vip_cycle).first())
    if query_app is None:
        return '找不到对应app信息-' + str(app_type) + '-' + str(vip_type) + '-' + str(vip_cycle),


    try:
        # 自动兑换逻辑
        if app_type == 'iqy':
            iqiyi_invoke(country_code, phone_num, phone_code_url, redeem.redeem_code)
        if app_type == 'mgtv':
            mgtv_invoke(country_code, phone_num, phone_code_url, redeem.redeem_code)
        if app_type == 'wps':
            wps_invoke(country_code, phone_num, phone_code_url, redeem.redeem_code)
        if app_type == 'txsp':
            wps_invoke(country_code, phone_num, phone_code_url, redeem.redeem_code)
        if app_type == 'yksp':
            wps_invoke(country_code, phone_num, phone_code_url, redeem.redeem_code)
    except Exception as e:
        msg = country_code + phone_num + '-自动兑换逻辑报错-' + app_type + '-' + vip_type + '-' + vip_cycle
        return jsonify({'msg': msg}), 200


    # app会员ID
    app_vip_id = str(uuid.uuid4())[0:8]

    url_addr = str(uuid.uuid4()).replace('-', '')

    # app会员表插入一条数据
    new_app_vip = AppVip(
        app_vip_id=app_vip_id,
        app_type=app_type,
        country_code=country_code,
        phone_num=phone_num,
        url_addr=url_addr,
        url_create_at=datetime.now(),
        vip_type=redeem.vip_type,
        vip_cycle=redeem.vip_cycle,
        vip_share_num=1,
        vip_share_remain=query_app.vip_share_total - 1,
        vip_exchange_code = redeem.redeem_code
    )
    db.session.add(new_app_vip)

    # 店铺会员增加一条数据
    new_shop_vip = ShopVip(
        app_vip_id=app_vip_id,
        country_code=country_code,
        phone_num=phone_num,
        app_type=app_type,
        vip_type=redeem.vip_type,
        url_addr=url_addr,
        vip_create_at=datetime.now(),
        url_valid=1
    )
    db.session.add(new_shop_vip)

    db.session.commit()

    return 1


@main.route('/phone/batch_exchange_vip', methods=['POST'])
def batch_exchange_vip():
    params = request.get_json()
    batch_data = params.get('batch_data', None)
    vip_type = params.get('vip_type', None)
    vip_cycle = params.get('vip_cycle', None)
    result = []
    for data in batch_data:
        res = exchange_vip_method(data.get('country_code'), data.get('phone_num'), data.get('phone_code_url'), data.get('app_type'), vip_type, vip_cycle)
        if res == 1:
            result.append('兑换成功')
        else:
            result.append(res)

    return jsonify({'msg': result, 'code': 1}), 200


@main.route('/app_vip/search', methods=['POST'])
def get_app_vip_page():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = AppVip.query
    phone_num = params.get('phone_num', None)
    app_type = params.get('app_type', None)
    vip_type = params.get('vip_type', None)
    result = []

    sql = '''select a.vip_share_total,
                    IFNULL(t.used, 0) as used,
                    (a.vip_share_total - IFNULL(t.used, 0)) as vip_last,
                    av.id, av.app_vip_id, av.app_type, av.country_code, av.phone_num, av.url_addr, av.url_create_at, av.vip_type, av.vip_cycle, av.vip_share_num, av.vip_share_remain, av.vip_exchange_code
             from app_vip av
             left join app a on av.app_type = a.app_name and av.vip_type = a.vip_type and av.vip_cycle = a.vip_cycle
             left join (select app_type, count(*) as used, country_code, phone_num
                     from shop_vip
                     group by country_code, phone_num, app_type) t
             on av.app_type = t.app_type and av.country_code = t.country_code and av.phone_num = t.phone_num where 1 = 1'''

    if phone_num is not None and phone_num != '':
        query = query.filter(AppVip.phone_num.contains(phone_num))
        sql = sql + ' and av.phone_num = "' + str(phone_num) + '"'
    if app_type is not None and app_type != '':
        query = query.filter(AppVip.app_type == app_type)
        sql = sql + ' and av.app_type = "' + str(app_type) + '"'
    if vip_type is not None and vip_type != '':
        query = query.filter(AppVip.vip_type == vip_type)
        sql = sql + ' and av.vip_type = "' + str(vip_type) + '"'

    sql = sql + ' limit ' + str(page_offset) + ',' + str(page_size)
    total = query.count()

    res = db.session.execute(text(sql)).fetchall()
    for r in res:
        result.append({
            'id': r[3],
            'app_vip_id': r[4],
            'app_type': r[5],
            'country_code': r[6],
            'phone_num': r[7],
            'url_addr': r[8],
            'url_create_at': r[9].strftime('%Y-%m-%d %H:%M:%S'),
            'vip_type': r[10],
            'vip_cycle': r[11],
            'vip_share_num': r[1],
            'vip_share_remain': r[2],
            'vip_exchange_code': r[14],
            'base_path': app.Config.base_path
        })
    return jsonify({'total': total, 'list': result}), 200

# 生成链接
@main.route('/app_vip/url', methods=['POST'])
def get_url():
    params = request.get_json()
    country_code = params.get('country_code', None)
    phone_num = params.get('phone_num', None)
    app_type = params.get('app_type', None)

    app_vip = (AppVip.query.filter(AppVip.country_code == country_code)
                             .filter(AppVip.phone_num == phone_num)
                             .filter(AppVip.app_type == app_type).first())

    if app_vip is None:
        return jsonify({
            'msg': '未查询到app会员信息-' + country_code + "-" + phone_num + "-" + app_type
        }), 200

    url_addr = str(uuid.uuid4()).replace('-', '')

    new_shop_vip = ShopVip(
        app_vip_id=app_vip.app_vip_id,
        country_code=country_code,
        phone_num=phone_num,
        app_type=app_type,
        vip_type=app_vip.vip_type,
        url_addr=url_addr,
        vip_create_at=datetime.now(),
        url_valid=1
    )
    db.session.add(new_shop_vip)
    db.session.commit()

    return jsonify({'url': app.Config.base_path + url_addr, 'msg': '生成成功'}), 200

@main.route('/app_manage/search', methods=['POST'])
def get_app_page():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = App.query
    result = []
    total = query.count()
    app_list = query.limit(page_size).offset(page_offset)
    for app in app_list:
        result.append({
            'id': app.id,
            'app_name': app.app_name,
            'vip_type': app.vip_type,
            'vip_cycle': app.vip_cycle,
            'vip_share_total': app.vip_share_total,
            'create_at': app.create_at
        })
    return jsonify({'total': total, 'list': result}), 200

@main.route('/redeem_code/search', methods=['POST'])
def get_redeem_code_page():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = RedeemCode.query
    result = []
    total = query.count()
    redeem_code_list = query.limit(page_size).offset(page_offset)
    for redeem_code in redeem_code_list:
        result.append({
            'id': redeem_code.id,
            'redeem_code': redeem_code.redeem_code,
            'app_name': redeem_code.app_name,
            'vip_type': redeem_code.vip_type,
            'vip_cycle': redeem_code.vip_cycle,
            'use_status': redeem_code.use_status,
            'create_at': redeem_code.create_at
        })
    return jsonify({'total': total, 'list': result}), 200

# 兑换码模版下载
@main.route('/redeem_code/download', methods=['POST'])
def redeem_template_download():
    wb = Workbook()
    ws = wb.active
    ws.title = 'Sheet'
    ws.append(["序号", "兑换码", "app名称", "会员类型", "会员周期"])
    ws.append(["1", "xxxx-1234-xxxx-4567", "iqy", "vip", "month_1"])
    ws.append(["2", "xxxx-2345-xxxx-5678", "mgtv", "svip", "month_3"])
    ws.append(["", "", "", "", ""])
    ws.append(["app类型对应关系", "实际值", "展示值", "", ""])
    ws.append(["", "mgtv", "芒果tv", "", ""])
    ws.append(["", "txsp", "腾讯视频", "", ""])
    ws.append(["", "iqy", "爱奇艺", "", ""])
    ws.append(["", "wps", "WPS", "", ""])
    ws.append(["", "yksp", "优酷视频", "", ""])
    ws.append(["", "", "", "", ""])
    ws.append(["会员周期对应关系", "实际值", "展示值", "", ""])
    ws.append(["", "day_1", "1天", "", ""])
    ws.append(["", "month_1", "1个月", "", ""])
    ws.append(["", "month_3", "1季度", "", ""])
    ws.append(["", "month_6", "半年", "", ""])
    ws.append(["", "month_12", "1年", "", ""])
    output = BytesIO()
    wb.save(output)
    output.seek(0)

    return send_file(output,
                     as_attachment=False,
                     download_name='兑换码模版.xlsx',
                     mimetype='application/vnd.ms-excel')

# 兑换码导入
@main.route('/redeem_code/upload', methods=['POST'])
def redeem_code_upload():
    file = request.files['file']

    wb = load_workbook(file)
    ws = wb.worksheets[0]

    for row in ws.iter_rows(min_row=2, values_only=True):
        try:
            new_redeem_code = RedeemCode(
                redeem_code = row[1],
                app_name = row[2],
                vip_type = row[3],
                vip_cycle = row[4]
            )

            db.session.add(new_redeem_code)
            db.session.commit()

        except Exception as e:
            db.session.rollback()

    return jsonify({'msg':'上传成功'}), 200


@main.route('/shop_vip/search', methods=['POST'])
def get_shop_vip_page():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = ShopVip.query
    result = []
    total = query.count()
    shop_vip_list = query.limit(page_size).offset(page_offset)
    for shop_vip in shop_vip_list:
        result.append({
            'id': shop_vip.id,
            'app_vip_id': shop_vip.app_vip_id,
            'app_type': shop_vip.app_type,
            'vip_type': shop_vip.vip_type,
            'url_addr': shop_vip.url_addr,
            'shop_vip_id': shop_vip.shop_vip_id,
            'vip_create_at': shop_vip.vip_create_at.strftime('%Y-%m-%d %H:%M:%S'),
            'url_valid': shop_vip.url_valid,
            'create_at': shop_vip.create_at,
            'base_path': app.Config.base_path
        })
    return jsonify({'total': total, 'list': result}), 200


@main.route('/shop_vip/export', methods=['GET', 'POST'])
def export_shop_vip():
    params = request.get_json()
    page_size = params.get('page_size', 20)
    page_offset = (params.get('page_num', 1) - 1) * page_size
    query = ShopVip.query
    result = []
    shop_vip_list = query.limit(page_size).offset(page_offset)
    for shop_vip in shop_vip_list:
        result.append({
            'id': shop_vip.id,
            'app_vip_id': shop_vip.app_vip_id,
            'app_type': shop_vip.app_type,
            'vip_type': shop_vip.vip_type,
            'url_addr': app.Config.base_path + shop_vip.url_addr,
            'shop_vip_id': shop_vip.shop_vip_id,
            'vip_create_at': shop_vip.vip_create_at,
            'url_valid': shop_vip.url_valid,
            'create_at': shop_vip.create_at
        })

    wb = Workbook()
    ws = wb.active
    ws.title = 'Sheet'
    ws.append(["序号", "APP会员ID", "APP类型", "会员类型", "用户url地址", "店铺会员ID", "会员生成日期", "是否失效"])
    for shop_vip in shop_vip_list:
        ws.append([
            shop_vip.id,
            shop_vip.app_vip_id,
            shop_vip.app_type,
            shop_vip.vip_type,
            shop_vip.url_addr,
            shop_vip.shop_vip_id,
            shop_vip.vip_create_at,
            shop_vip.url_valid
        ])
    output = BytesIO()
    wb.save(output)
    output.seek(0)

    file_name = '店铺会员导出-' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '.xlsx'

    return send_file(output,
                     as_attachment=True,
                     download_name=file_name,
                     mimetype='application/vnd.ms-excel')
# 删除链接
@main.route('/shop_vip/del_url', methods=['POST'])
def shop_vip_del_url():
    params = request.get_json()
    code = params.get('code', None)

    shop_vip = ShopVip.query.filter(ShopVip.url_addr==code).first()
    if shop_vip is None:
        return jsonify({'msg': '未找到会员信息'})

    db.session.delete(shop_vip)
    db.session.commit()

    return jsonify({'msg': '链接删除成功'}), 200

# 失效链接
@main.route('/shop_vip/invalid_url', methods=['POST'])
def shop_vip_invalid_url():
    params = request.get_json()
    code = params.get('code', None)
    shop_vip = ShopVip.query.filter(ShopVip.url_addr==code).first()
    if shop_vip is None:
        return jsonify({'msg': '未找到会员信息'})

    shop_vip.url_valid = 0
    db.session.commit()

    return jsonify({'msg': '链接失效成功'}), 200

# 获取管理员信息
@main.route('/user', methods=['GET'])
@admin_required
def get_current_user():
    token = request.headers.get('Authorization')
    if not token:
        return jsonify({'message': 'Token is missing'}), 401

    try:
        data = jwt.decode(token.split()[1], os.getenv('SECRET_KEY', 'secret'), algorithms=['HS256'])
        user = User.query.filter_by(id=data['user_id'], role='admin').first()
        if not user:
            return jsonify({'message': 'Admin not found'}), 404

        return jsonify({
            'id': user.id,
            'username': user.username,
            'role': user.role
        }), 200
    except:
        return jsonify({'message': 'Token is invalid'}), 401

@main.route('/admin/users', methods=['GET'])
@admin_required
def get_all_users():
    users = User.query.all()
    output = []

    for user in users:
        user_data = {
            'id': user.id,
            'username': user.username,
            'role': user.role,
            'status': user.status
        }
        output.append(user_data)

    return jsonify({'users': output}), 200


@main.route('/admin/users/<int:id>/ban', methods=['PUT'])
@admin_required
def ban_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    user.status = False
    db.session.commit()
    return jsonify({'message': 'User banned successfully'}), 200


@main.route('/admin/users/<int:id>/unban', methods=['PUT'])
@admin_required
def unban_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    user.status = True
    db.session.commit()
    return jsonify({'message': 'User unbanned successfully'}), 200

@main.route('/admin/users/<int:id>', methods=['PUT'])
@admin_required
def update_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    user_data = request.get_json()
    if 'username' in user_data:
        user.username = user_data['username']
    if 'role' in user_data:
        user.role = user_data['role']

    db.session.commit()
    return jsonify({'message': 'User updated successfully'}), 200

@main.route('/admin/users', methods=['POST'])
@admin_required
def create_user():
    user_data = request.get_json()
    if not user_data.get('username') or not user_data.get('password'):
        return jsonify({'message': 'Username and password are required'}), 400

    try:
        hashed_password = bcrypt.hashpw(user_data['password'].encode('utf-8'), bcrypt.gensalt())
        new_user = User(
            username=user_data['username'],
            password=hashed_password.decode('utf-8'),
            role=user_data.get('role', 'user'),
            status=True
        )

        db.session.add(new_user)
        db.session.commit()

        return jsonify({
            'message': 'User created successfully',
            'user_id': new_user.id
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': 'Failed to create user', 'error': str(e)}), 500

@main.route('/admin/users/<int:id>', methods=['DELETE'])
@admin_required
def delete_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    # 先删除用户的所有关联comments
    for comment in user.comments:
        db.session.delete(comment)

    # 再删除用户的所有关联posts
    for post in user.posts:
        db.session.delete(post)

    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully'}), 200


# app新增修改
@main.route('/app_manage/', methods=['POST'])
def app_add():
    params = request.get_json()
    app_name = params.get('app_name', None)
    vip_type = params.get('vip_type', None)
    vip_cycle = params.get('vip_cycle', None)
    vip_share_total = params.get('vip_share_total', None)

    app_id = params.get('id', None)
    try:
        if app_id is None or app_id == '':
            new_app = App(
                app_name=app_name,
                vip_type=vip_type,
                vip_cycle=vip_cycle,
                vip_share_total=vip_share_total,
                create_at=datetime.now()
            )
            db.session.add(new_app)
            db.session.commit()
            return jsonify({'msg': '新增成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'msg': 'app会员重复'}), 200

    try:
        query_app = App.query.filter(App.id==app_id).first()
        query_app.app_name = app_name
        query_app.vip_type = vip_type
        query_app.vip_cycle = vip_cycle
        query_app.vip_share_total = vip_share_total

        db.session.add(query_app)
        db.session.commit()

        return jsonify({'msg': '更新成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'msg': 'app会员重复'}), 200

# app删除
@main.route('/app_manage/del', methods=['POST'])
def app_del():
    params = request.get_json()
    app_id = params.get('id', None)

    if not app_id:
        return jsonify({'msg': '未找到app'}), 200

    query_app = App.query.filter(App.id==app_id).first()

    query_app_vip = AppVip.query.filter(AppVip.app_type==query_app.app_name).filter(AppVip.vip_type==query_app.vip_type).filter(AppVip.vip_cycle==query_app.vip_cycle).first()
    if query_app_vip is not None:
        return jsonify({'msg': '不可删除'}), 200

    db.session.delete(query_app)
    db.session.commit()

    return jsonify({'msg': '删除成功'}), 200

# 兑换码新增修改
@main.route('/redeem_manage/', methods=['POST'])
def redeem_add():
    params = request.get_json()
    redeem_code = params.get('redeem_code', None)
    app_name = params.get('app_name', None)
    vip_type = params.get('vip_type', None)
    vip_cycle = params.get('vip_cycle', None)
    use_status = params.get('use_status', None)

    redeem_id = params.get('id', None)
    try:
        if not redeem_id:
            new_redeem_code = RedeemCode(
                redeem_code=redeem_code,
                app_name=app_name,
                vip_type=vip_type,
                vip_cycle=vip_cycle,
                use_status=use_status,
                create_at=datetime.now()
            )
            db.session.add(new_redeem_code)
            db.session.commit()
            return jsonify({'msg': '新增成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'msg': '兑换码重复'}), 200

    try:
        query_redeem = RedeemCode.query.filter(RedeemCode.id==redeem_id).first()
        query_redeem.redeem_code = redeem_code
        query_redeem.app_name = app_name
        query_redeem.vip_type = vip_type
        query_redeem.vip_cycle = vip_cycle
        query_redeem.use_status = use_status

        db.session.add(query_redeem)
        db.session.commit()

        return jsonify({'msg': '更新成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'msg': '兑换码重复'}), 200

# 兑换码删除
@main.route('/redeem_manage/del', methods=['POST'])
def redeem_del():
    params = request.get_json()
    redeem_id = params.get('id', None)

    if not redeem_id:
        return jsonify({'msg': '未找到兑换码'}), 200

    query_redeem = RedeemCode.query.filter(RedeemCode.id==redeem_id).first()
    db.session.delete(query_redeem)
    db.session.commit()

    return jsonify({'msg': '删除成功'}), 200

